/**
 * 函数防抖，默认最后一次点击后0.5秒触发
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
export const _debounce = (fn, t, immediate = false) => {
  let delay = t || 500;
  let timer;

  return function () {
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      timer = null

      fn.apply(this, args)
    }, delay)
    if (immediate) {
      immediate = false
      fn.apply(this, args)
    }
  }
};


/**
 * 函数节流，默认间隔1秒触发
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
function _throttle(fn, t) {
  let last;
  let timer;
  let interval = t || 1000;
  return function () {
    let args = arguments;
    let now = +new Date();
    if (last && now - last < interval) {
      clearTimeout(timer);
      timer = setTimeout( function(){
        last = now;
      }, interval);
    } else {
      last = now;
      fn.apply(this, args);
    }
  }
};



// immediate 表示第一次是否立即执行
export function _debounce2(fn, wait = 50) {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)

    if (window.immediate) {
      fn.apply(this, args)
    }

    timer = setTimeout(() => {
      fn.apply(this, args)
    }, wait)
  }
}
